/**
 * Mobile Responsive JavaScript
 * 移动端响应式交互脚本
 * 
 * @package WP Bootstrap Woo
 */

(function($) {
    'use strict';

    const MobileResponsive = {
        isMobile: false,
        isTablet: false,
        touchStartX: 0,
        touchStartY: 0,
        touchEndX: 0,
        touchEndY: 0,

        init: function() {
            this.detectDevice();
            this.initMobileNavigation();
            this.initTouchGestures();
            this.initMobileOptimizations();
            this.initMobileToolbar();
            this.initMobileBottomNav();
            this.initProductGalleryMobile();
            this.initMobileFilters();
            this.bindEvents();
        },

        // 设备检测
        detectDevice: function() {
            const userAgent = navigator.userAgent.toLowerCase();
            const width = window.innerWidth;
            
            this.isMobile = width <= 768 || /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(userAgent);
            this.isTablet = width > 768 && width <= 1024;
            
            // 添加设备类到body
            if (this.isMobile) {
                $('body').addClass('is-mobile');
            } else if (this.isTablet) {
                $('body').addClass('is-tablet');
            } else {
                $('body').addClass('is-desktop');
            }
        },

        // 移动端导航菜单
        initMobileNavigation: function() {
            if (!this.isMobile) return;

            // 创建移动端菜单结构
            this.createMobileMenu();
            
            // 菜单切换按钮
            $(document).on('click', '.mobile-menu-toggle', this.toggleMobileMenu);
            
            // 关闭菜单
            $(document).on('click', '.mobile-menu-close, .mobile-menu-overlay', this.closeMobileMenu);
            
            // 子菜单切换
            $(document).on('click', '.mobile-nav .dropdown-toggle', this.toggleSubmenu);
        },

        // 创建移动端菜单
        createMobileMenu: function() {
            if ($('.mobile-menu-overlay').length) return;
            
            const menuHtml = `
                <div class="mobile-menu-overlay"></div>
                <button class="mobile-menu-toggle navbar-toggler">
                    <span class="navbar-toggler-icon"></span>
                </button>
            `;
            
            $('body').append(menuHtml);
            
            // 克隆主导航到移动端菜单
            const mainNav = $('.navbar-nav').clone();
            mainNav.addClass('mobile-nav');
            $('.navbar-collapse').append(mainNav);
            
            // 添加关闭按钮
            $('.navbar-collapse').prepend('<button class="mobile-menu-close">&times;</button>');
        },

        // 切换移动端菜单
        toggleMobileMenu: function(e) {
            e.preventDefault();
            $('.navbar-collapse, .mobile-menu-overlay').toggleClass('show');
            $('body').toggleClass('menu-open');
        },

        // 关闭移动端菜单
        closeMobileMenu: function() {
            $('.navbar-collapse, .mobile-menu-overlay').removeClass('show');
            $('body').removeClass('menu-open');
        },

        // 切换子菜单
        toggleSubmenu: function(e) {
            e.preventDefault();
            const $submenu = $(this).siblings('.dropdown-menu');
            $submenu.toggleClass('show');
            $(this).find('i').toggleClass('rotated');
        },

        // 触摸手势初始化
        initTouchGestures: function() {
            if (!this.isMobile) return;

            // 滑动手势
            $(document).on('touchstart', this.handleTouchStart.bind(this));
            $(document).on('touchend', this.handleTouchEnd.bind(this));
            
            // 产品图片滑动
            $(document).on('touchstart', '.product-gallery-mobile', this.handleGalleryTouchStart.bind(this));
            $(document).on('touchend', '.product-gallery-mobile', this.handleGalleryTouchEnd.bind(this));
        },

        // 处理触摸开始
        handleTouchStart: function(e) {
            const firstTouch = e.touches[0];
            this.touchStartX = firstTouch.clientX;
            this.touchStartY = firstTouch.clientY;
        },

        // 处理触摸结束
        handleTouchEnd: function(e) {
            if (!this.touchStartX || !this.touchStartY) return;
            
            const touch = e.changedTouches[0];
            this.touchEndX = touch.clientX;
            this.touchEndY = touch.clientY;
            
            this.handleSwipeGesture();
        },

        // 处理滑动手势
        handleSwipeGesture: function() {
            const deltaX = this.touchEndX - this.touchStartX;
            const deltaY = this.touchEndY - this.touchStartY;
            const minSwipeDistance = 50;
            
            if (Math.abs(deltaX) > Math.abs(deltaY)) {
                // 水平滑动
                if (Math.abs(deltaX) > minSwipeDistance) {
                    if (deltaX > 0) {
                        // 右滑
                        this.handleSwipeRight();
                    } else {
                        // 左滑
                        this.handleSwipeLeft();
                    }
                }
            }
            
            // 重置触摸坐标
            this.touchStartX = 0;
            this.touchStartY = 0;
            this.touchEndX = 0;
            this.touchEndY = 0;
        },

        // 右滑处理
        handleSwipeRight: function() {
            // 如果菜单关闭，右滑打开菜单
            if (!$('.navbar-collapse').hasClass('show')) {
                this.toggleMobileMenu({ preventDefault: () => {} });
            }
        },

        // 左滑处理
        handleSwipeLeft: function() {
            // 如果菜单打开，左滑关闭菜单
            if ($('.navbar-collapse').hasClass('show')) {
                this.closeMobileMenu();
            }
        },

        // 移动端优化
        initMobileOptimizations: function() {
            if (!this.isMobile) return;

            // 防止iOS缩放
            this.preventIOSZoom();
            
            // 优化滚动
            this.optimizeScrolling();
            
            // 延迟加载优化
            this.optimizeLazyLoading();
            
            // 表单优化
            this.optimizeForms();
        },

        // 防止iOS缩放
        preventIOSZoom: function() {
            $('input, select, textarea').on('focus', function() {
                $('meta[name=viewport]').attr('content', 'width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no');
            }).on('blur', function() {
                $('meta[name=viewport]').attr('content', 'width=device-width, initial-scale=1, user-scalable=yes');
            });
        },

        // 优化滚动
        optimizeScrolling: function() {
            // 添加平滑滚动
            $('a[href^="#"]').on('click', function(e) {
                e.preventDefault();
                const target = $(this.getAttribute('href'));
                if (target.length) {
                    $('html, body').animate({
                        scrollTop: target.offset().top - 80
                    }, 300);
                }
            });
            
            // 滚动时隐藏地址栏
            let lastScrollTop = 0;
            $(window).scroll(function() {
                const scrollTop = $(this).scrollTop();
                if (scrollTop > lastScrollTop && scrollTop > 100) {
                    // 向下滚动
                    $('.mobile-toolbar').addClass('hidden');
                } else {
                    // 向上滚动
                    $('.mobile-toolbar').removeClass('hidden');
                }
                lastScrollTop = scrollTop;
            });
        },

        // 优化延迟加载
        optimizeLazyLoading: function() {
            if ('IntersectionObserver' in window) {
                const imageObserver = new IntersectionObserver((entries) => {
                    entries.forEach(entry => {
                        if (entry.isIntersecting) {
                            const img = entry.target;
                            img.src = img.dataset.src;
                            img.classList.add('loaded');
                            imageObserver.unobserve(img);
                        }
                    });
                }, {
                    rootMargin: '50px 0px'
                });

                $('img[data-src]').each(function() {
                    imageObserver.observe(this);
                });
            }
        },

        // 表单优化
        optimizeForms: function() {
            // 自动调整输入框大小
            $('textarea').each(function() {
                this.style.height = 'auto';
                this.style.height = this.scrollHeight + 'px';
            });

            // 表单验证视觉反馈
            $('input, select, textarea').on('blur', function() {
                const $this = $(this);
                if (this.checkValidity()) {
                    $this.removeClass('is-invalid').addClass('is-valid');
                } else {
                    $this.removeClass('is-valid').addClass('is-invalid');
                }
            });
        },

        // 移动端工具栏
        initMobileToolbar: function() {
            if (!this.isMobile) return;

            const toolbarHtml = `
                <div class="mobile-toolbar">
                    <div class="toolbar-left">
                        <button class="mobile-menu-toggle toolbar-btn">
                            <i class="feather-menu"></i>
                        </button>
                    </div>
                    <div class="toolbar-center">
                        <img src="${wbw_ajax.theme_url}/assets/images/logo.png" alt="Logo" class="logo">
                    </div>
                    <div class="toolbar-right">
                        <button class="toolbar-btn search-toggle">
                            <i class="feather-search"></i>
                        </button>
                        <a href="${wbw_ajax.site_url}/cart" class="toolbar-btn cart-btn">
                            <i class="feather-shopping-cart"></i>
                            <span class="cart-count">0</span>
                        </a>
                    </div>
                </div>
            `;

            $('body').prepend(toolbarHtml).addClass('has-mobile-toolbar');
        },

        // 移动端底部导航
        initMobileBottomNav: function() {
            if (!this.isMobile) return;

            const bottomNavHtml = `
                <div class="mobile-bottom-nav">
                    <a href="${wbw_ajax.site_url}" class="nav-item">
                        <i class="feather-home nav-icon"></i>
                        <span class="nav-label">Home</span>
                    </a>
                    <a href="${wbw_ajax.site_url}/shop" class="nav-item">
                        <i class="feather-grid nav-icon"></i>
                        <span class="nav-label">Shop</span>
                    </a>
                    <a href="${wbw_ajax.site_url}/cart" class="nav-item">
                        <i class="feather-shopping-cart nav-icon"></i>
                        <span class="nav-label">Cart</span>
                    </a>
                    <a href="${wbw_ajax.site_url}/my-account" class="nav-item">
                        <i class="feather-user nav-icon"></i>
                        <span class="nav-label">Account</span>
                    </a>
                </div>
            `;

            $('body').append(bottomNavHtml).addClass('has-mobile-bottom-nav');
            
            // 高亮当前页面
            this.highlightCurrentPage();
        },

        // 高亮当前页面
        highlightCurrentPage: function() {
            const currentUrl = window.location.pathname;
            $('.mobile-bottom-nav .nav-item').each(function() {
                const href = $(this).attr('href');
                if (href && currentUrl.includes(href.split('/').pop())) {
                    $(this).addClass('active');
                }
            });
        },

        // 产品图片画廊移动端
        initProductGalleryMobile: function() {
            if (!this.isMobile) return;

            $('.product-gallery').each(function() {
                const $gallery = $(this);
                const images = $gallery.find('img');
                
                if (images.length > 1) {
                    $gallery.addClass('product-gallery-mobile');
                    
                    // 创建滑块容器
                    const slidesHtml = '<div class="product-gallery-slides"></div>';
                    const indicatorsHtml = '<div class="product-gallery-indicators"></div>';
                    
                    $gallery.wrapInner(slidesHtml);
                    $gallery.append(indicatorsHtml);
                    
                    // 创建指示器
                    images.each(function(index) {
                        const indicator = `<span class="product-gallery-indicator ${index === 0 ? 'active' : ''}" data-slide="${index}"></span>`;
                        $gallery.find('.product-gallery-indicators').append(indicator);
                    });
                    
                    // 绑定指示器点击事件
                    $gallery.on('click', '.product-gallery-indicator', function() {
                        const slideIndex = $(this).data('slide');
                        MobileResponsive.goToSlide($gallery, slideIndex);
                    });
                }
            });
        },

        // 处理画廊触摸开始
        handleGalleryTouchStart: function(e) {
            const touch = e.touches[0];
            this.galleryStartX = touch.clientX;
        },

        // 处理画廊触摸结束
        handleGalleryTouchEnd: function(e) {
            if (!this.galleryStartX) return;
            
            const touch = e.changedTouches[0];
            const deltaX = touch.clientX - this.galleryStartX;
            const minSwipeDistance = 50;
            
            if (Math.abs(deltaX) > minSwipeDistance) {
                const $gallery = $(e.currentTarget);
                const currentSlide = $gallery.find('.product-gallery-indicator.active').data('slide');
                const totalSlides = $gallery.find('.product-gallery-indicator').length;
                
                let nextSlide;
                if (deltaX > 0) {
                    // 右滑 - 上一张
                    nextSlide = currentSlide > 0 ? currentSlide - 1 : totalSlides - 1;
                } else {
                    // 左滑 - 下一张
                    nextSlide = currentSlide < totalSlides - 1 ? currentSlide + 1 : 0;
                }
                
                this.goToSlide($gallery, nextSlide);
            }
            
            this.galleryStartX = 0;
        },

        // 跳转到指定滑块
        goToSlide: function($gallery, slideIndex) {
            const $slides = $gallery.find('.product-gallery-slides');
            const slideWidth = $gallery.width();
            const translateX = -slideIndex * slideWidth;
            
            $slides.css('transform', `translateX(${translateX}px)`);
            
            // 更新指示器
            $gallery.find('.product-gallery-indicator').removeClass('active');
            $gallery.find('.product-gallery-indicator').eq(slideIndex).addClass('active');
        },

        // 移动端筛选器
        initMobileFilters: function() {
            if (!this.isMobile) return;

            // 创建移动端筛选器按钮
            if ($('.shop-filters').length === 0 && $('.woocommerce-products-header').length > 0) {
                const filtersHtml = `
                    <div class="shop-filters">
                        <button class="filter-btn" data-filter="sort">
                            <i class="feather-sliders"></i>
                            Sort
                        </button>
                        <button class="filter-btn" data-filter="filter">
                            <i class="feather-filter"></i>
                            Filter
                        </button>
                        <button class="filter-btn" data-filter="view">
                            <i class="feather-grid"></i>
                            View
                        </button>
                    </div>
                `;
                
                $('body').append(filtersHtml);
            }
            
            // 筛选器按钮点击事件
            $(document).on('click', '.shop-filters .filter-btn', this.handleFilterClick);
        },

        // 处理筛选器点击
        handleFilterClick: function(e) {
            const filterType = $(this).data('filter');
            
            switch (filterType) {
                case 'sort':
                    MobileResponsive.showSortOptions();
                    break;
                case 'filter':
                    MobileResponsive.showFilterOptions();
                    break;
                case 'view':
                    MobileResponsive.toggleViewMode();
                    break;
            }
        },

        // 显示排序选项
        showSortOptions: function() {
            const sortOptions = `
                <div class="mobile-modal">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h4>Sort Products</h4>
                            <button class="modal-close">&times;</button>
                        </div>
                        <div class="modal-body">
                            <div class="sort-options">
                                <label><input type="radio" name="sort" value="popularity"> Popularity</label>
                                <label><input type="radio" name="sort" value="rating"> Average Rating</label>
                                <label><input type="radio" name="sort" value="date"> Newest</label>
                                <label><input type="radio" name="sort" value="price"> Price: Low to High</label>
                                <label><input type="radio" name="sort" value="price-desc"> Price: High to Low</label>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button class="btn-apply">Apply</button>
                        </div>
                    </div>
                </div>
            `;
            
            $('body').append(sortOptions);
            $('.mobile-modal').addClass('show');
        },

        // 显示筛选选项
        showFilterOptions: function() {
            $('.shop-sidebar').addClass('show');
            $('.shop-sidebar-overlay').addClass('show');
        },

        // 切换视图模式
        toggleViewMode: function() {
            const $products = $('.woocommerce ul.products');
            $products.toggleClass('list-view');
        },

        // 绑定通用事件
        bindEvents: function() {
            // 模态框关闭
            $(document).on('click', '.mobile-modal .modal-close, .mobile-modal .modal-backdrop', function() {
                $('.mobile-modal').remove();
            });
            
            // 侧边栏关闭
            $(document).on('click', '.shop-sidebar-close, .shop-sidebar-overlay', function() {
                $('.shop-sidebar, .shop-sidebar-overlay').removeClass('show');
            });
            
            // 搜索切换
            $(document).on('click', '.search-toggle', function() {
                $('.search-form').toggle();
            });
            
            // 窗口大小变化时重新检测设备
            $(window).on('resize', this.detectDevice.bind(this));
            
            // 阻止过度滚动
            $(document).on('touchmove', function(e) {
                if ($('body').hasClass('menu-open')) {
                    e.preventDefault();
                }
            });
        }
    };

    // 文档加载完成后初始化
    $(document).ready(function() {
        MobileResponsive.init();
    });

    // 全局暴露
    window.MobileResponsive = MobileResponsive;

})(jQuery);